#!/bin/bash
# Сравниваем версии пакеты в двух заданных репозиториях

set -efu

# задаем параметры
repo1="rosa2021.1"
repo2="rosa2021.15"
arch="x86_64"
# main, contrib, non-free
repo=main

TOKEN="${TOKEN:-}"

tmp="$(mktemp -d)"
# чтобы при следующих вызовах mktemp создавал файлы и папки уже внутри $tmp
export TMPDIR="$tmp"

_trap(){
	if [ "${NOCLEANTMP:-0}" = 1 ]; then return; fi
	rm -fr "$tmp"
}
trap '_trap' EXIT

# bash-5.1.16-2.src.rpm -> bash
_sourcerpm2name(){
	echo "$1" | rev | cut -d '-' -f 3- | rev
}

_normalize(){
	local p1
	local p2
	local p3
	while read -r -a line
	do
		# %{sourcerpm}
		p1="${line[0]}"
		# %{name}
		p2="${line[1]}"
		# %{epoch}:%{version}-%{release}
		p3="${line[2]}"
		p1="$(_sourcerpm2name "$p1")"
		echo "$p1 $p2 $p3"
	done
}

dnf_conf="$tmp"/dnf.conf
cat > "$dnf_conf" << EOF
[main]
arch=${arch}
basearch=${arch}
ignorearch=True
reposdir=/dev/null

[repo_main]
name=repo_main
baseurl=https://${TOKEN}abf-downloads.rosalinux.ru/\$releasever/repository/${arch}/main/release/
gpgcheck=0
enabled=0

[repo_contrib]
name=repo_contrib
baseurl=https://${TOKEN}abf-downloads.rosalinux.ru/\$releasever/repository/${arch}/contrib/release/
gpgcheck=0
enabled=0

[repo_non-free]
name=repo_non-free
baseurl=https://${TOKEN}abf-downloads.rosalinux.ru/\$releasever/repository/${arch}/non-free/release/
gpgcheck=0
enabled=0 

# SRPM repos are not used yet
[repo_main-source]
name=repo_main
baseurl=https://${TOKEN}abf-downloads.rosalinux.ru/\$releasever/repository/SRPMS/main/release/
gpgcheck=0
enabled=0
[repo_contrib-source]
name=repo_contrib
baseurl=https://${TOKEN}abf-downloads.rosalinux.ru/\$releasever/repository/SRPMS/contrib/release/
gpgcheck=0
enabled=0
[repo_non-free-source]
name=repo_non-free
baseurl=https://${TOKEN}abf-downloads.rosalinux.ru/\$releasever/repository/SRPMS/non-free/release/
gpgcheck=0
enabled=0
EOF

dnf --config "$dnf_conf" \
	--releasever "$repo1" \
	--disablerepo '*' \
	--enablerepo repo_"$repo" \
	repoquery \
	--qf '%{sourcerpm} %{name} %{epoch}:%{version}-%{release}' \
> "$tmp"/f1_repo1_"$repo"
cat "$tmp"/f1_repo1_"$repo" | _normalize | sort -u > "$tmp"/f2_repo1_"$repo"

dnf --config "$dnf_conf" \
	--releasever "$repo2" \
	--disablerepo '*' \
	--enablerepo repo_"$repo" \
	repoquery \
	--qf '%{sourcerpm} %{name} %{epoch}:%{version}-%{release}' \
> "$tmp"/f1_repo2_"$repo"
cat "$tmp"/f1_repo2_"$repo" | _normalize | sort -u > "$tmp"/f2_repo2_"$repo"

echo "$tmp"
diff -u --color "$tmp"/f2_repo1_"$repo" "$tmp"/f2_repo2_"$repo"
